<template>
 <!-- 甲供清单 -->
    <div>
        <div class="e-table" style="background-color: #fff" v-if="showTable">
            <!-- 头部buttons -->
            <div class="top" v-if="isAdd">
                <div class="left">
                    <div>
                        <el-button size="small" class="btn-greenYellow" @click="importList"
                        >新增</el-button>
                    </div>
                </div>
                <div class="right">
                    <div class="squarecolor">
                        <div class="color colorAdd"></div>
                        <span>新增</span>
                    </div>
                    <div class="squarecolor item">
                        <div class="color colorUpdate"></div>
                        <span>修改</span>
                    </div>
                    <div class="squarecolor">
                        <div class="color colorDel"></div>
                        <span>删除/过期</span>
                    </div>
                </div>
            </div>
            <div class="e-tree-table">
                <div class="errorMsg" v-if="errorMsg.length>0">
                    <span >
                        {{ errorMsg.join(',') }}
                    </span>
                </div>
                <el-table
                    ref="tableRef"
                        border
                        style="width: 100%"
                        row-key="billId"
                        :data="tableData"
                        :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren'
                        }"
                        :load="onload"
                        lazy
                        :row-class-name="tableRowClassName"
                        class="table"
                        :max-height="$store.state.tableHeight"
                        v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'tableRef' }"
                    >
                        <el-table-column prop="code" label="操作" width="200" align="left">
                            <template slot-scope="{ row }">
                                <div class="oparation_box" v-if="!row.mainMaterialFlag">
                                    <img src="@/assets/btn/sub.png" class="add_sub"
                                        @click="addChilden(row)"
                                        v-if="row.hierarchyType === 1 && isAdd"
                                        title="添加子级"
                                     />
                                    <i class="el-icon-delete"
                                        style="font-size: 24px; color: #e9513e;"
                                        v-if="isAdd && row.changeState !== -1"
                                        @click="onDelNode(row)"
                                        title="删除"
                                    ></i>
                                    <img src="@/assets/btn/cancelDelete.png" class="cancel_delete"
                                        @click="cancelDelete(row)"
                                            v-if="isAdd && row.changeState === -1"
                                        title="取消删除"
                                    />
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="supplyType"
                            label="甲供类型"
                            width="200"
                        >
                            <template slot-scope="{ row }">

                                <el-select
                                    v-if="!row.mainMaterialFlag && row.hierarchyType === 1  && isAdd"
                                    v-model="row.supplyType"
                                    @change="changeSupplyType(row)"
                                >
                                    <el-option
                                        v-for="item in supplyType"
                                        :value="item.value"
                                        :label="item.label"
                                        :key="item.value"
                                        :disabled="isDisabled(item.value)"
                                    >
                                    </el-option>
                                </el-select>
                                <span v-else>
                                    <span v-if="row.hierarchyType === 1">{{  row.supplyType ? supplyType.find(x=>x.value === row.supplyType).label:'' }}</span>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="materialType"
                            label="物资类别"
                            min-width="250"
                        >
                            <template slot-scope="{ row }">
                                <el-input v-model="row.materialType" v-if="!row.mainMaterialFlag && row.hierarchyType === 2 && isAdd" readonly>
                                    <i
                                        class="
                                            el-icon-document-copy
                                        "
                                        slot="suffix"
                                        id="select"
                                        @click="selectMaterialType(row)"
                                    >
                                    </i>
                                </el-input>
                                <span v-else-if="row.mainMaterialFlag && row.hierarchyType === 2">{{ row.materialType }}</span>
                                <span v-else></span>
                            </template>
                        </el-table-column>
                        <el-table-column
                             prop="materialName"
                            label="物资名称"
                            min-width="200"
                            align="left"
                        >
                            <template slot-scope="{ row }">
                                 <span v-if="row.hierarchyType === 3">{{row.mainMaterialFlag ? row.materialName :'--' }}</span>
                                <span v-else></span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="model"
                            label="规格型号"
                            width="200"
                        >
                            <template slot-scope="{ row }">
                                <span>{{row.mainMaterialFlag ? row.model :'--' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="unit"
                            label="单位"
                            width="120"
                        >
                            <template slot-scope="{ row }">
                                <span>{{row.mainMaterialFlag ? row.unit :'--' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                           prop="structuralPosition"
                            label="结构部位"
                            min-width="200"
                            align="left"
                        >
                            <template slot-scope="{ row }">
                                <span>{{row.mainMaterialFlag ? row.structuralPosition :'--' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="drawingNumber"
                            label="图纸理论数量"
                            width="120"
                        >
                            <template slot-scope="{ row }">
                                <span>{{row.mainMaterialFlag ? row.drawingNumber :'--' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="lossCoefficient"
                            label="耗损系数(%)"
                            width="120"
                        >
                            <template slot-scope="{ row }">
                                <span>{{row.mainMaterialFlag ? row.lossCoefficient :'--' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="number"
                            label="合计数量"
                            width="120"
                            align="right"
                        >
                            <template slot-scope="{ row }">
                                <span>{{row.mainMaterialFlag ? row.number :'--' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="unitPrice"
                            label="单价" class-name="historyData"
                            width="120"
                            align="right"
                        >
                            <template slot-scope="{ row }">
                                    <el-input v-if="row.mainMaterialFlag && row.hierarchyType === 3 && isEdit" v-model="row.unitPrice" @change="unitPriceChange(row)" v-enterJustFloat></el-input>
                                    <span v-else-if="row.hierarchyType === 4">{{ row.unitPrice }}</span>
                                    <span v-else>--</span>
                                    <historyUpdateTable
                                        v-if="checkEmpty(row.priceRecords)"
                                        @clickIcon="clickIcon(row.priceRecords)"
                                    />
                            </template>
                        </el-table-column>
                        <el-table-column prop="amount" width="120" label="金额" class-name="historyData" align="left">
                             <template slot-scope="{ row }">
                                    <el-input v-if="!row.mainMaterialFlag  && row.children.length === 0 && isEdit && !(row.supplyType === 1 && row.hierarchyType === 1) && row.supplyType !== ''" v-model="row.amount" @change="changeAmount(row)" v-enterJustFloat></el-input>
                                    <span v-else>{{ row.amount  }}</span>
                                    <historyUpdateTable
                                        v-if="checkEmpty(row.amountRecords)"
                                        @clickIcon="clickIcon(row.amountRecords)"
                                    />
                            </template>
                        </el-table-column>
                </el-table>
            </div>
         </div>
    </div>
</template>
<script>
// import tenderRequest from '@/api/tender/tender.js'
import { toLocation, vueDom } from '@/utils/common.js'
import { uidBuilder } from '@/api/base/uid.js'
import { getUnit } from '@/api/subcontractApi/currency.js'
import { isFourInput, isNumInput, isTwoInput } from '@/utils/rules.js'
import { mapState, mapMutations } from 'vuex'
import { selectDataClient } from '@/utils/common'
import historyUpdateTable from '@/pages/subcontract/components/historyUpdateTable.vue'
import fn from '@/utils/checkEmpty.js'
export default {
    props: {
        detailsOfProposed: {
            type: Array,
            default: function () {
                return []
            }
        },
        tenderClass: {
            type: String,
            default: ''
        },
        billid: {
            type: String,
            default: ''
        },
        contractListTable: {
            type: Array,
            default: function () {
                return []
            }
        },
        errorMsg: {
            type: Array,
            default: function () {
                return []
            }
        },
        isBidding: {
            type: Boolean,
            default: false
        },
        mainInfo: {
            type: Object,
            default: function () {
                return {}
            }
        },
        auditState: {
            type: Object,
            default: function () {
                return {
                    canAudit: false,
                    canModify: true,
                    canUndoAudit: false,
                    freeNextUnits: [],
                    isFree: false,
                }
            }
        },
        //是否可以新增
        isAdd: {
            default: true
        },
        //是否可以编辑
        isEdit: {
            default: true
        },
        formData: {
            type: Object,
            default: function () {
                return {}
            }
        },
        subcontract: { //接口
        },
        state: { //流程状态
            type: Number
        }
    },
    model: {
        prop: 'contractListTable',
        event: 'change'
    },
    computed: {
        tenderId () {
            return this.$route.query.billid
        },
        ...mapState({
            materialList: state => state.contract.ctClassify.materialList,
            supplyType: state => state.contract.ctClassify.supplyTypeList
        }),
        //判断数据是否为空
        checkEmpty () {
            return datas=>{
                return !fn.checkEmpty(datas)
            }
        },
        //甲供类型禁用项
        isDisabled () {
            return value =>{
                const supplyTypeList = this.tableData.filter(x=>(x.supplyType && x.changeState !== -1)).map(x=>x.supplyType)
                const obj = supplyTypeList.find(x=>x == value)
                if(obj) {
                    return true
                }else{
                    return false
                }
            }
        },

    },
    components: {
        historyUpdateTable,
    },
    watch: {
        contractListTable: {
            handler (newName) {
                this.tableData = newName
            },
            immediate: true,
            deep: true
        },
        tableData: {
            handler (newName) {
                this.$emit('change', newName)
            },
            immediate: true,
            deep: true
        },
        materialList: {
            handler (newData) { //计算甲供清单
                if(newData.length === 0) return
                this.materialListTeam.push(newData)
                const fn = ()=>{
                    if(this.materialListIndex === this.materialListTeam.length - 1) {
                        const item = this.materialListTeam[this.materialListIndex]
                        const params = {
                            'codeList': [newData.itemNo],
                            'limit': 0,
                            'page': 0,
                            'structureList': [newData.structureId]
                        }
                        this.subcontract.getMaterialPlanDtl(params).then(res=>{
                            if(res && res.length > 0) {
                                const setStructure = async (material, data, materialClass, parent, resolve)=>{ //设置结构层数据
                                    const uid = await this.uidBuilder({ num: 1 })
                                    const structure = {
                                        'amount': '',
                                        'billId': '',
                                        'drawingNumber': 0,
                                        'hierarchyType': 4,
                                        'lossCoefficient': data.coefficient,
                                        'mainMaterialFlag': true,
                                        'materialName': '',
                                        'materialType': '',
                                        'model': data.spec, //规格型号
                                        'number': 0,
                                        'parentId': '',
                                        'sourceId': this.billid,
                                        'structuralPosition': '',
                                        'structureId': '',
                                        'supplyType': 1,
                                        'unit': '',
                                        'unitPrice': 0,
                                        'changeType': 1,
                                        'changeState': 1,
                                        'listRelation': ''
                                    }
                                    let listRelation  = structure.listRelation ? JSON.parse(structure.listRelation) : []
                                    //data：物资理论计划数据 item:合同清单带入的数据
                                    if(item.operation) { //如果是删除则找出那一条数据将数量变为0
                                        const obj = listRelation.find(x=>x.structureId === item.structureId && x.itemNo === item.itemNo && x.billId === item.billId)
                                        if(obj) {
                                            obj.qty  = 0
                                        }
                                    }else{
                                        const obj = listRelation.find(x=>x.structureId === item.structureId && x.itemNo === item.itemNo)
                                        if(obj) {
                                            obj.qty  = data.qty
                                            obj.billId = item.billId
                                        }
                                        else{
                                            const obj = {
                                                structureId: item.structureId,
                                                itemNo: item.itemNo,
                                                billId: item.billId,
                                                qty: data.qty,
                                            }
                                            listRelation.push(obj)
                                        }
                                    }
                                    structure.drawingNumber = listRelation.reduce((prev, item)=>{
                                        return prev + ((item.changeState !== -1) ? item.qty : 0)
                                    }, 0)
                                    structure.listRelation = JSON.stringify(listRelation)
                                    structure.number = structure.drawingNumber * (1 + data.coefficient)
                                    structure.amount = structure.number * structure.unitPrice
                                    structure.structureId = item.structureId
                                    structure.structuralPosition = item.structureName
                                    structure.unit = data.unit
                                    structure.billId = uid
                                    structure.sourceId = this.billid
                                    structure.parentId = material.billId
                                    structure.children = []
                                    structure.hasChildren = false
                                    structure.materialName =  material.materialName
                                    structure.materialNameId = material.materialNameId
                                    structure.materialType = material.materialType
                                    structure.materialClass =  material.materialClass
                                    material.children.push(structure)
                                    this.mapTableData[material.billId] = material
                                    this.onCalcAmount(structure)
                                    if(item.operation) { //如果是删除则找出那一条数据将数量变为0
                                        const obj = listRelation.find(x=>x.structureId === item.structureId && x.itemNo === item.itemNo && x.billId === item.billId)
                                        if(obj) {
                                            this.deleteBranch(structure, material, materialClass, parent)
                                        }
                                    }
                                    resolve()
                                }
                                const setMaterial = async (materialClass, data, parent, resolve)=>{ //设置物资层数据
                                    const uid = await this.uidBuilder({ num: 1 })
                                    const material = {
                                        'amount': '',
                                        'billId': '',
                                        'drawingNumber': 0,
                                        'hierarchyType': 3,
                                        'lossCoefficient': 0,
                                        'mainMaterialFlag': true,
                                        'materialName': '',
                                        'materialType': '',
                                        'model': '',
                                        'number': 0,
                                        'parentId': '',
                                        'sourceId': this.billid,
                                        'structuralPosition': '',
                                        'structureId': '',
                                        'supplyType': 1,
                                        'unit': '',
                                        'unitPrice': 0,
                                        'changeType': 1,
                                        'changeState': 1,
                                    }
                                    material.children = []
                                    material.hasChildren = true
                                    material.parentId = materialClass.billId
                                    material.billId = uid
                                    material.materialName = data.materialName
                                    material.materialNameId = data.materialId
                                    materialClass.materialType = data.levelPathName
                                    materialClass.materialTypeId = data.levelPathId
                                    setStructure(material, data, materialClass, parent, resolve)
                                    materialClass.children.push(material)
                                    this.mapTableData[materialClass.billId] = materialClass
                                }
                                const setMaterialClass = async (parent, data, resolve)=>{ //设置物资类别层数据
                                    const uid = await this.uidBuilder({ num: 1 })
                                    const materialClass = {
                                        'amount': 0,
                                        'billId': '',
                                        'drawingNumber': 0,
                                        'hierarchyType': 2,
                                        'lossCoefficient': 0,
                                        'mainMaterialFlag': true,
                                        'materialName': '',
                                        'materialType': '',
                                        'model': '',
                                        'number': 0,
                                        'parentId': '',
                                        'sourceId': this.billid,
                                        'structuralPosition': '',
                                        'structureId': '',
                                        'supplyType': 1,
                                        'unit': '',
                                        'unitPrice': 0,
                                        'changeType': 1,
                                    }
                                    materialClass.children = []
                                    materialClass.hasChildren = true
                                    materialClass.parentId = parent.billId
                                    materialClass.billId = uid
                                    materialClass.materialType = data.materialClassName
                                    materialClass.materialTypeId = data.materialClassId
                                    setMaterial(materialClass, data, parent, resolve)
                                    parent.children.push(materialClass)
                                    this.mapTableData[parent.billId] = parent
                                }
                                let parent = this.tableData.find(x=>x.mainMaterialFlag === true)
                                const setParent = async parent=>{ //设置甲供类型层数据
                                    parent.changeType = parent.changeType === 1 ? 1 : 2
                                    parent.changeState = parent.changeState === 1 ? 1 : 2
                                    parent.hasChildren = true
                                    const setData = data=>{
                                        return new Promise(resolve=>{
                                            let materialClass =  parent.children.find(x=>x.materialTypeId === data.materialClassId)
                                            if(materialClass) {
                                                materialClass.changeType = materialClass.changeType === 1 ? 1 : 2
                                                materialClass.changeState = materialClass.changeState === 1 ? 1 : 2
                                                let material = materialClass.children.find(x=>x.materialNameId === data.materialId)
                                                if(material) {
                                                    material.changeType = material.changeType === 1 ? 1 : 2
                                                    material.changeState =  material.changeState === 1 ? 1 : 2
                                                    let structure = material.children.find(x=>x.structureId === item.structureId)
                                                    if(structure) {
                                                        let listRelation  = structure.listRelation ? JSON.parse(structure.listRelation) : []
                                                        //data：物资理论计划数据 item:合同清单带入的数据
                                                        if(item.operation) { //如果是删除则找出那一条数据将数量变为0
                                                            const obj = listRelation.find(x=>x.structureId === item.structureId && x.itemNo === item.itemNo && x.billId === item.billId)
                                                            if(obj) {
                                                                obj.qty  = 0
                                                            }
                                                        }else{
                                                            const obj = listRelation.find(x=>x.structureId === item.structureId && x.itemNo === item.itemNo)
                                                            if(obj) {
                                                                obj.qty  = data.qty
                                                                obj.billId = item.billId
                                                            }
                                                            else{
                                                                const obj = {
                                                                    structureId: item.structureId,
                                                                    itemNo: item.itemNo,
                                                                    billId: item.billId,
                                                                    qty: data.qty,
                                                                }
                                                                listRelation.push(obj)
                                                            }
                                                        }
                                                        structure.drawingNumber = listRelation.reduce((prev, item)=>{
                                                            return prev + ((item.changeState !== -1) ? item.qty : 0)
                                                        }, 0)
                                                        structure.listRelation = JSON.stringify(listRelation)
                                                        structure.number = structure.drawingNumber * (1 + data.coefficient)
                                                        structure.amount = structure.number * structure.unitPrice
                                                        structure.changeType = structure.changeType === 1 ? 1 : 2
                                                        structure.changeState = structure.changeState === 1 ? 1 : 2
                                                        this.onCalcAmount(structure)
                                                        if(item.operation) { //如果是删除则找出那一条数据将数量变为0
                                                            const obj = listRelation.find(x=>x.structureId === item.structureId && x.itemNo === item.itemNo && x.billId === item.billId)
                                                            if(obj) {
                                                                this.deleteBranch(structure, material, materialClass, parent)
                                                            }
                                                        }
                                                        resolve()
                                                    }else{
                                                        setStructure(material, data, materialClass, parent, resolve)
                                                    }
                                                }else{
                                                    setMaterial(materialClass, data, parent, resolve)
                                                }
                                            }else{
                                                setMaterialClass(parent, data, resolve)
                                            }
                                        })
                                    }
                                    for(let index = 0;index < res.length;index++) {
                                        await setData(res[index], index).then()
                                        if(index === res.length - 1) {
                                            this.materialListIndex++
                                            fn()
                                        }
                                    }
                                }
                                if(parent) {
                                    parent.changeType = 2
                                    parent.changeState = 2
                                    setParent(parent)
                                }else{
                                    this.uidBuilder({ num: 1 }).then(uid=>{
                                        const parent = {
                                            'amount': '',
                                            'billId': '',
                                            'drawingNumber': 0,
                                            'hierarchyType': 1,
                                            'lossCoefficient': 0,
                                            'mainMaterialFlag': true,
                                            'materialName': '',
                                            'materialType': '',
                                            'model': '',
                                            'number': 0,
                                            'parentId': '',
                                            'sourceId': this.billid,
                                            'structuralPosition': '',
                                            'structureId': '',
                                            'supplyType': 1,
                                            'unit': '',
                                            'unitPrice': 0,
                                            'changeType': 1,
                                            'changeState': 1,
                                        }
                                        parent.mainMaterialFlag = true
                                        parent.supplyType = 1
                                        parent.parentId = '0'
                                        parent.billId = uid
                                        parent.children = []
                                        parent.hasChildren = true
                                        setParent(parent)
                                        this.tableData.unshift(parent)

                                    })
                                }
                            }else{
                                this.materialListIndex++
                                fn()
                            }
                        }).catch(err => {
                            this.materialListIndex++
                            fn()
                            console.log('this.twoTodoListerr', err)
                        })

                    }
                }
                if(!this.timer) {
                    this.timer = setTimeout(() => {
                        fn()
                        clearTimeout(this.timer)
                        this.timer = null
                    }, 100)
                }
            },
            immediate: false,
            deep: true
        },
        'formData.nailDetailedListState': {
            handler (newName) {
                console.log('newName', newName)
            },
            immediate: true,
            deep: true
        }
    },
    data () {
        return {
            detailsOfProposedArr: [],
            tableData: [],
            mapTableData: {},
            addList: [], // 缓存新增数据
            unitList: [],
            searchKey: '',
            isSearch: false,
            materialListTeam: [], //存储执行队列
            materialListIndex: 0,
            showTable: true,
            timer: null,
        }
    },
    created () {
        this.getData()
        this.setMaterialList([])
    },
    mounted () {
        vueDom(
            // 默认0为选中项
            () => {
                $('.el-tree-node:first')?.addClass('is-current')
            },
            () => {
                return $('.el-tree-node:first')?.attr('class')?.includes('is-current')
            }
        )
        getUnit().then(res=>{
            let arr = res.map(x=>{
                let obj = {
                    value: '',
                    label: '',
                }
                obj.value = x.kvValue
                obj.label = x.kvKey
                return obj
            })
            this.unitList = arr
        })
    },
    methods: {
        ...mapMutations(
            'contract', ['setMaterialList']
        ),
        ...mapMutations(['setHistoryTableData']),
        //根据id查询甲供清单
        getData () {
            this.showTable = false
            //获取物资清单
            this.subcontract.getSupplyMaterialList({
                sourceId: this.billid,
            }).then(res => {
                res = res.code ? [] : res
                res.forEach(item=>{
                    if(this.state === 1) {
                        item.quantityUpdateFlag = false
                        item.unitPriceUpdateFlag = false
                        item.amountUpdateFlag = false
                    }
                })
                //平级列表转成树形结构
                let arr = []
                const fn = (data, parentId)=>{
                    let arr = res.filter(x=>x.parentId === parentId)
                    if(arr.length > 0) {
                        arr.forEach(item=>{
                            let isDetailed = res.find(x=>x.parentId === item.billId)
                            item.hasChildren = isDetailed ? true : false
                            item.changeType = 0
                            item.children = []
                            if(item.hasChildren) {
                                fn(item.children, item.billId)
                            }
                            this.mapTableData[item.billId] = item
                            data.push(item)
                        })
                    }
                }
                fn(arr, '0')
                this.tableData = arr
                this.mapTableData['0'] = {
                    children: this.tableData
                }
                this.showTable = true
            })
        },
        // 通过id获取子级数据
        async getById (billId) {
            const params = {
                parentId: billId,
                sourceId: this.billid
            }
            let result = await this.getTableData(params)
            result.forEach(item=>{
                item.hasChildren = item.isDetailed ? false : true
                item.changeType = 0
            })
            return result
        },
        importList () {
            this.showClient()
        },
        async showClient () {
            const uid = await this.uidBuilder({ num: 1 })
            let obj = {
                'amount': '',
                'billId': uid,
                'changeType': 1,
                'changeState': 1,
                'children': [],
                'drawingNumber': 0,
                'lossCoefficient': 0,
                'materialName': '',
                'materialType': '',
                'model': '',
                'number': 0,
                'parentId': '0',
                'sourceId': this.billid,
                'structuralPosition': '',
                'supplyType': '',
                'unit': '',
                'unitPrice': 0,
                'mainMaterialFlag': false,
                'hierarchyType': 1,
                hasChildren: false,
                isNew: true
            }
            this.tableData.push(obj)
            this.mapTableData['0'] = {
                children: this.tableData
            }
        },
        async onload (row, treeNode, resolve) {
            let result
            if(row.children.length > 0) {
                result = row.children
            }else{
                // 如果有缓存数据，说明是点击的 “添加子级” 按钮
                if (this.addList.length > 0) {
                    result = result.concat(this.addList)
                    this.addList = []
                }
            }
            row.treeNode = treeNode
            row.resolve = resolve
            row.children = result
            this.mapTableData[row.billId] = row
            resolve(result)
        },
        // 添加子级
        async addChilden (row) {
            if(!row.supplyType) {
                this.clientPop('err', '请选择甲供类型')
                return
            }
            const children = row.children.filter(x=>x.changeState !== -1).map(x=>{
                const arr = x.materialTypeId.split('/')
                return arr[arr.length - 1]
            })
            const ids = children
            selectDataClient({
                SelectServiceToken: '/material/categoryLibrary/queryListByParentClassId', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({
                    'parentiId': '0',
                    'topClassNameNeedless': ['主要材料']
                }), //初始化参数
                Title: '选择物资' // 标题
            }).then( value => {
                value.forEach(async val=>{
                    const repeat = row.children.filter(x=>{
                        return x.materialTypeId.indexOf(val.levelPathId) !== -1 && x.changeState !== -1
                    })
                    if(repeat.length > 0) {
                        repeat[0].materialTypeId = val.levelPathId
                        repeat[0].materialType = val.levelPathName
                        repeat[0].changeType = repeat[0].changeType === 1 ? 1 : 2
                        repeat[0].changeState = repeat[0].changeState === 1 ? 1 : 2
                    }else{
                        const { billId } = row
                        const { hierarchyType } = row
                        const uid = await this.uidBuilder({ num: 1 })
                        const addData = {
                            'amount': '',
                            'changeType': 1,
                            'changeState': 1,
                            'children': [],
                            'drawingNumber': 0,
                            'lossCoefficient': 0,
                            'materialName': '',
                            'materialType': val.levelPathName,
                            'materialTypeId': val.levelPathId,
                            'model': '',
                            'number': 0,
                            'parentId': billId,
                            'sourceId': this.billid,
                            'structuralPosition': '',
                            'supplyType': row.supplyType,
                            'unit': '',
                            'unitPrice': 0,
                            'mainMaterialFlag': false,
                            'hierarchyType': hierarchyType + 1,
                            listIsDetailed: false,
                            billId: uid, //本级ID
                            hasChildren: false,
                            isNew: true
                        }
                        const tableRef = this.$refs.tableRef
                        if (!this.mapTableData[billId]) {
                        // 缓存新增数据
                            this.addList.push(addData)
                            // 如果是最子级，则设为目录
                            if (!row.hasChildren) {
                                row.children = row.children ? row.children : []
                                row.children = row.children.length > 0 ? row.children.push(addData) : [addData]
                                row.hasChildren = true
                                this.mapTableData[uid] = row
                                // 切换展开状态
                                this.$nextTick(() => {
                                // tableRef.toggleRowExpansion(row, true)
                                    tableRef.store.loadOrToggle(row)
                                })
                                // }
                            } else {
                            // 展开子级
                            // tableRef.store.loadData(row, billId)
                                tableRef.store.loadOrToggle(row)
                            }
                        } else {
                        // 已经展开，则直接添加
                            row.children.push(addData)
                            row.hasChildren = true
                        }
                        // 定位到新添加行
                        toLocation(addData)
                    }

                })
            })

        },
        onDelNode (row) {
            // 如果是新增的，则直接删除
            if (row.changeType === 1 && row.changeState === 1) {
                const siblings = this.mapTableData[row.parentId].children
                const index = siblings.findIndex(item => item.billId === row.billId)
                siblings.splice(index, 1)
            }else if(row.changeType !== 1 && row.changeState === 1) {
                // 否则先提示，再删除
                this.clientPop('err', this.oneDeleteListErr, () => {
                    if(row.parentId === '0') {
                        row.changeType = -1
                        row.changeState = -1
                    }else{
                        const fn = row=>{
                            row.changeType = -1
                            row.changeState = -1
                            if(row.children.length > 0) {
                                row.children.forEach(item=>{
                                    fn(item)
                                })
                            }
                            this.onCalcAmount(row)
                            this.mapTableData[row.billId] = row
                        }
                        fn(row)
                        row.isDetailed = true
                        if(row.parentId !== '0') {
                            const parent = this.mapTableData[row.parentId]
                            const filterSibings = parent.children.filter(x=>(x.changeState !== -1))
                            if(filterSibings.length === 0) {
                                parent.hasChildren = false
                            }
                        }
                    }

                })
            }
            else {
                // 否则先提示，再删除
                this.clientPop('err', this.oneDeleteListErr, () => {
                    console.log('row', row)
                    const fn = row=>{
                        row.changeType = -2
                        row.changeState = -1
                        if(row.children.length > 0) {
                            row.children.forEach(item=>{
                                fn(item)
                            })
                        }
                        this.onCalcAmount(row)
                        this.mapTableData[row.billId] = row
                    }
                    fn(row)
                })
            }
        },
        // 输入后计划金额
        onCalcAmount (row) {
            if(row.mainMaterialFlag) {
                row.amount = (row.changeState !== -1) ? parseInt(( parseFloat(row.number) ? parseFloat(row.number) : 0 ) * ( parseFloat(row.unitPrice) ? parseFloat(row.unitPrice) : 0 )) : 0
            }
            if(row.changeState !== -1) {
                row.changeType = row.changeType === 1 ? 1 : 2
                row.changeState = row.changeState === 1 ? 1 : 2
            }
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'billId',
                parentField: 'parentId',
                row
            })
        },
        // 递归统计父级
        // recurCount ({ parentId, rootId, listField, parentField, row }) {
        //     // 到根节点
        //     if (parentId === rootId) {
        //         return
        //     }
        //     const parent = this.mapTableData[parentId]
        //     // 统计所有同级
        //     let countSibling = parent.children.reduce((prev, item) => {
        //         item.amount = item.amount ? parseFloat(item.amount) : item.amount
        //         return prev + ((item.changeState !== -1) ? item.amount : 0)
        //     }, 0)
        //     // 赋值汇总数据给父级
        //     countSibling = typeof (countSibling) === 'string' ? parseFloat(countSibling) : countSibling
        //     parent.amount = parseFloat(countSibling.toFixed(2))
        //     if((parent.changeType !== -1 && parent.changeType !== -2)) {
        //         parent.changeType = parent.changeType === 1 ? 1 : 2
        //         parent.changeState = parent.changeState === 1 ? 1 : 2
        //     }
        //     // 未到根节点则继续遍历父节点
        //     return this.recurCount({
        //         parentId: parent[parentField],
        //         rootId,
        //         listField,
        //         parentField,
        //         row,
        //     })
        // },
        recurCount ({ parentId }) {
            let treeId = parentId
            while(treeId || treeId !== '0') {
                const parent = this.mapTableData[treeId]
                if(!parent) return
                // 统计所有同级
                let countSibling = parent.children.reduce((prev, item) => {
                    item.amount = item.amount ? parseFloat(item.amount) : item.amount
                    return prev + ((item.changeState !== -1) ? item.amount : 0)
                }, 0)
                // 赋值汇总数据给父级
                countSibling = typeof (countSibling) === 'string' ? parseFloat(countSibling) : countSibling
                parent.amount = parseFloat(countSibling.toFixed(2))
                if((parent.changeType !== -1 && parent.changeType !== -2)) {
                    parent.changeType = parent.changeType === 1 ? 1 : 2
                    parent.changeState = parent.changeState === 1 ? 1 : 2
                }
                if(parent.parentId === treeId) return
                treeId = parent.parentId
            }
        },
        tableRowClassName ({ row }) {
            if(row.changeType === -1) {
                return `class-${row.billId} row-hide`
            }else{
                if(row.changeState === 1) {
                    return `class-${row.billId} green row-show`
                }else if(row.changeState === 2) {
                    return `class-${row.billId} yellow row-show`
                }else if(row.changeState === -1) {
                    return `class-${row.billId} red row-show`
                }else{
                    return `class-${row.billId} row-show`
                }
            }
        },

        async uidBuilder (params) {
            let temp = ''
            await uidBuilder(params).then(res => {
                temp = res.length === 1 ? res[0] : res
            })
            return temp
        },
        // refreshLoadTree (parentId) {
        //     // 根据父级id取出对应节点数据
        //     // const { row, treeNode, resolve } = this.mapTableData[parentId]
        //     let children = this.mapTableData[parentId].children
        //     const tableRef = this.$refs.tableRef
        //     this.$set(tableRef.store.states.lazyTreeNodeMap, parentId, children)
        // },

        isFourInput (event) {
            isFourInput(event)
        },
        isNumInput (event) {
            isNumInput(event)
        },
        isTwoInput (event) {
            isTwoInput(event)
        },
        //单价类型切换
        unitPriceTypeChange (row) {
            const fn = data=>{
                data.forEach(item=>{
                    item.unitPriceType = row.unitPriceType
                    if(!item.isDetailed) {
                        fn(item.children)
                    }
                    this.mapTableData[row.billId] = row
                })
            }
            if(!row.isDetailed) {
                fn(row)
            }else{
                this.mapTableData[row.billId] = row
            }
        },
        //单价切换
        unitPriceChange (row) {
            if(this.state === 1) {
                row.unitPriceUpdateFlag = true
            }
            row.children.forEach(item=>{
                item.unitPrice = row.unitPrice
                this.mapTableData[item.billId] = item
                this.onCalcAmount(item)
            })
            this.mapTableData[row.billId] = row
        },
        //金额切换
        changeAmount (row) {
            if(this.state === 1) {
                row.amountUpdateFlag = true
            }
            this.onCalcAmount(row)
        },
        //数量切换
        quantityChange (row) {
            const parent = this.mapTableData[row.parentId]
            // 统计所有同级
            const countSibling = parent.children.reduce((prev, item) => {
                return prev + Math.round((item.changeState !== -1) ? item.quantity : 0)
            }, 0)
            // 赋值汇总数据给父级
            parent.quantity = countSibling // 赋值汇总数据给父级
        },
        selectMaterialType (row) {
            const arr = row.materialTypeId.split('/')
            const ids  = arr.slice(-1)
            selectDataClient({
                SelectServiceToken: '/material/categoryLibrary/queryListByParentClassId', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({
                    'parentiId': '0',
                    'topClassNameNeedless': ['主要材料']
                }), //初始化参数
                Title: '选择物资' // 标题
            }).then(val => {
                const repeat = this.mapTableData[row.parentId].children.filter(x=>{
                    return x.materialTypeId.split('/')[0] === val[0].levelPathId.split('/')[0] && x.billId !== row.billId &&  row.changeState !== -1
                })
                if(repeat.length > 0) {
                    this.clientPop('err', '有重复或上下级包含关系的类别，请重新选择')
                }else{
                    row.materialType = val[0].levelPathName
                    row.materialTypeId = val[0].levelPathId
                    row.changeType = row.changeType === 1 ? 1 : 2
                    row.changeState = row.changeState === 1 ? 1 : 2
                }

            })
        },
        clearData () {
            const arr = [ ...this.tableData]
            const deleteFn = row=>{
                const deleteStru = row=>{//删除结构部位
                    const siblings = this.mapTableData[row.parentId].children
                    const index = siblings.findIndex(x=>x.billId === row.billId)
                    if(siblings[index].changeType === 1 && siblings[index].changeState === 1) {
                        siblings.splice(index, 1)
                    }else if(siblings[index].changeType !== 1 && siblings[index].changeState === 1) {
                        siblings[index].changeType = -1
                        siblings[index].changeState = -1
                    }
                    else{
                        siblings[index].changeType = -2
                        siblings[index].changeState = -1
                    }
                    this.onCalcAmount(row)
                }

                const fn1 = data=>{ //向下删除
                    if(data.children.length > 0) {
                        for(let i = 0;i < data.children.length;i++)
                        {
                            fn1(data.children[i])
                            if(data.children[i].changeType === 1 && data.children[i].changeState === 1) {
                                data.children.splice(i, 1)
                                i--
                            }else if(data.children[i].changeType !== 1 && data.children[i].changeState === 1) {
                                data.children[i].changeType = -1
                                data.children[i].changeState = -1
                            }
                            else{
                                data.children[i].changeType = -2
                                data.children[i].changeState = -1
                            }
                            this.onCalcAmount(data.children[i])
                        }
                    }else{
                        deleteStru(data)
                    }
                }
                fn1(row)
                const fn = data=>{ //向上删除
                    if(data.parentId !== '0') {
                        const siblings = this.mapTableData[data.parentId].children
                        const index = siblings.findIndex(x=>x.billId === data.billId)
                        const filterSibings = siblings.filter(x=>x.changeType !== -1)
                        if(filterSibings.length > 1) {
                            if(siblings[index].changeType === 1 && siblings[index].changeState === 1) {
                                siblings.splice(index, 1)
                            }else if(siblings[index].changeType !== 1 && siblings[index].changeState === 1) {
                                siblings[index].changeType = -1
                                siblings[index].changeState = -1
                            }
                            else{
                                siblings[index].changeType = -2
                                siblings[index].changeState = -1
                            }
                            this.onCalcAmount(siblings[index])
                        }else{
                            fn(this.mapTableData[data.parentId])
                            if(siblings[index].changeType === 1 && siblings[index].changeState === 1) {
                                siblings.splice(index, 1)
                            }else if(siblings[index].changeType !== 1 && siblings[index].changeState === 1) {
                                siblings[index].changeType = -1
                                siblings[index].changeState = -1
                            }
                            else{
                                siblings[index].changeType = -2
                                siblings[index].changeState = -1
                            }
                        }
                    }else{
                        const index = this.tableData.findIndex(x=>x.billId === data.billId)

                        if(this.tableData[index].changeType === 1 && this.tableData[index].changeState === 1) {
                            this.tableData.splice(index, 1)
                        }else if(this.tableData[index].changeType !== 1 && this.tableData[index].changeState === 1) {
                            this.tableData[index].changeType = -1
                            this.tableData[index].changeState = -1
                        }
                        else{
                            this.tableData[index].changeType = -2
                            this.tableData[index].changeState = -1
                        }
                        this.mapTableData['0'].children = this.tableData
                    }
                }
                fn(row)
            }
            arr.forEach(item=>{
                deleteFn(item)
            })
        },
        clickIcon (list) {
            this.setHistoryTableData(list)
        },
        //删除当前分支
        deleteBranch (structure, material, materialClass, parent) {
            if(material.children.length > 1) {
                //删除结构部位层
                if(structure.changeType !== 1 && structure.changeState !== 1) {
                    structure.changeType = -2
                    structure.changeState = -1
                }else if(structure.changeType !== 1 && structure.changeState === 1) {
                    structure.changeType = -1
                    structure.changeState = -1
                }
                else{
                    let structureIndex = material.children.findIndex(x=>x.structureId === structure.structureId)
                    material.children.splice(structureIndex, 1)
                }
            }else{
                if(structure.changeType !== 1 && structure.changeState !== 1) {
                    structure.changeType = -2
                    structure.changeState = -1
                }else if(structure.changeType !== 1 && structure.changeState === 1) {
                    structure.changeType = -1
                    structure.changeState = -1
                }else{
                    material.children.splice(0, 1)
                }
                if(materialClass.children.length > 1) {
                    //删除物资层
                    if(material.changeType !== 1 && material.changeState !== 1) {
                        material.changeType = -2
                        material.changeState = -1
                    }else if(material.changeType !== 1 && material.changeState === 1) {
                        material.changeType = -1
                        material.changeState = -1
                    }else{
                        let materialIndex = materialClass.children.find(x=>x.materialNameId === material.materialId)
                        materialClass.children.splice(materialIndex, 1)
                    }
                }
                else{
                    if(material.changeType !== 1 && material.changeState !== 1) {
                        material.changeType = -2
                        material.changeState = -1
                    }else if(material.changeType !== 1 && material.changeState === 1) {
                        material.changeType = -1
                        material.changeState = -1
                    }else{
                        materialClass.children.splice(0, 1)
                    }
                    if(parent.children.length > 1) {
                        //删除物资类别层
                        if(materialClass.changeType !== 1 && materialClass.changeState !== 1) {
                            materialClass.changeType = -2
                            materialClass.changeState = -1
                        }else if(materialClass.changeType !== 1 && materialClass.changeState === 1) {
                            materialClass.changeType = -1
                            materialClass.changeState = -1
                        }else{
                            let materialClassIndex =  parent.children.find(x=>x.materialTypeId === materialClass.materialClassId)
                            parent.children.splice(materialClassIndex, 1)
                        }
                    }else{
                        if(materialClass.changeType !== 1 && materialClass.changeState !== 1) {
                            materialClass.changeType = -2
                            materialClass.changeState = -1
                        }else if(materialClass.changeType !== 1 && materialClass.changeState === 1) {
                            materialClass.changeType = -1
                            materialClass.changeState = -1
                        }else{
                            parent.children.splice(0, 1)
                        }
                        if(parent.changeType !== 1 && parent.changeState !== 1) {
                            parent.changeType = -2
                            parent.changeState = -1
                        }else if(parent.changeType !== 1 && parent.changeState === 1) {
                            parent.changeType = -1
                            parent.changeState = -1
                        }else{
                            let parentIndex = this.tableData.findIndex(x=>x.mainMaterialFlag === true)
                            this.tableData.splice(parentIndex, 1)
                        }
                    }
                }
            }
        },
        //取消删除
        cancelDelete (row) {
            const fn = data=>{
                data.changeState = 2
                data.changeType = 2
                if(data.children.length > 0) {
                    data.children.forEach(item=>{
                        fn(item)
                    })
                }
            }
            fn(row)
        },
        //切换甲供类型
        changeSupplyType (row) {
            row.changeType = row.changeType === 1 ? 1 : 2
            row.changeState = row.changeState === 1 ? 1 : 2
            const fn = row=>{
                if(row.children.length > 0) {
                    row.children.forEach(item=>{
                        item.supplyType = row.supplyType
                        item.changeType = item.changeType === 1 ? 1 : 2
                        item.changeState = item.changeState === 1 ? 1 : 2
                        fn(item)
                    })
                }
            }
            fn(row)
        }
    }
}
</script>
<style lang='scss' scoped>
    ::v-deep .hide-icon{
        .el-table__expand-icon{
            display: none;
        }
    }
    ::v-deep.el-table__row{
        .cell{
            display: flex;
            align-items: center;
        }
        td:nth-child(5),td:nth-child(6),td:nth-child(7){
            .cell{
                display: block;
            }
        }
        td:nth-child(8),td:nth-child(9),td:nth-child(10),td:nth-child(11),td:nth-child(12){
            .cell{
                justify-content: flex-end;
            }
        }
    }
    ::v-deep .el-popover__reference-wrapper{
        display: flex;
        height: 100%;
    }
</style>
